package com.vecharm.app.utils

import android.util.Log
import com.vecharm.app.BuildConfig
import com.vecharm.app.bean.SessionBean
import okhttp3.*
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import okhttp3.logging.HttpLoggingInterceptor
import okio.Buffer
import java.io.IOException


object RequestManager {


    private val CONNECT_TIMEOUT = 3000    //连接超时时间
    private val READ_TIMEOUT = 3000       //读取超时时间
    private val WRITE_TIMEOUT = 3000      //写的超时时间


    private var retrofit = lazy {

        val logging = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message -> Log.e("httpRequest", message) })
        logging.level = HttpLoggingInterceptor.Level.BASIC

        val client = OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT.toLong(), TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT.toLong(), TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIMEOUT.toLong(), TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .addInterceptor(logging)
                .addInterceptor { chain ->


                    val oldRequest = chain.request();
                    var newRequestBuild: Request.Builder? = null;
                    val method = oldRequest.method();
                    var postBody = ""
                    if ("POST" == method) {
                        val formBodyBuilder = FormBody.Builder()
                        commonData().forEach { formBodyBuilder.add(it.key, it.value) }
                        newRequestBuild = oldRequest.newBuilder()

                        val formBody = formBodyBuilder.build()
                        postBody = bodyToString(oldRequest.body())
                        postBody += (if (postBody.isNotEmpty()) "&" else "") + bodyToString(formBody)
                        newRequestBuild.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"), postBody))
                    } else {
                        // 添加新的参数
                        val commonParamsUrlBuilder = oldRequest.url().newBuilder().scheme(oldRequest.url().scheme()).host(oldRequest.url().host())

                        commonData().forEach { commonParamsUrlBuilder.addQueryParameter(it.key, it.value) }

                        newRequestBuild = oldRequest.newBuilder().method(oldRequest.method(), oldRequest.body()).url(commonParamsUrlBuilder.build())
                    }
                    val newRequest = newRequestBuild
                            .addHeader("Accept", "application/json")
                            .addHeader("Accept-Language", "zh")
                            .build()

                    val response = chain.proceed(newRequest)
                    val mediaType = response.body()?.contentType()
                    val content = response.body()?.string()

                    return@addInterceptor response.newBuilder().body(okhttp3.ResponseBody.create(mediaType, content
                            ?: "")).build()

                }
                .build()

        return@lazy Retrofit.Builder()
//                .baseUrl("http://120.79.229.136")
                .baseUrl("https://www.easy-mock.com/mock/5bffc142bfe3e5204cd3a84c/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build()

    }

    private fun bodyToString(request: RequestBody?): String {
        try {
            val buffer = Buffer()
            if (request != null)
                request.writeTo(buffer)
            else
                return ""
            return buffer.readUtf8()
        } catch (e: IOException) {
            return "did not work"
        }
    }


    fun getRetrofit() = retrofit.value!!

    private fun commonData() = mapOf(
            "sessionId" to SessionBean.getSessionId(),
            "app_version" to BuildConfig.VERSION_CODE.toString(),
            "serial_number" to "1238434374",
            "app_name" to "SmartLabel"
    )


}